<template>
  <div class="search-container">
    <!-- 顶部的搜索栏 -->
    <form
      class="search-form"
      action="/"
    >
      <van-search
        v-model="searchText"
        show-action
        placeholder="请输入搜索关键词"
        @search="onSearch"
        @cancel="onCancel"
        @focus="isResultShow = false "
        background="#3296fa"
      />
    </form>
    <!-- 搜索结果 -->
    <searchResult
      v-if="isResultShow"
      :searchText='searchText'
    ></searchResult>
    <!-- 联想建议 -->
    <searchSuggestion
      v-else-if="searchText"
      :searchText='searchText'
      @search='onSearch'
    ></searchSuggestion>
    <!-- 搜索历史 -->
    <searchHistory
      v-else
      :search-histories='searchHistories'
      @clear-search-histories='searchHistories=[]'
      @search='onSearch'
    ></searchHistory>
  </div>
</template>

<script>
import searchHistory from './components/search-history.vue'
import searchSuggestion from './components/search-suggestion.vue'
import searchResult from './components/search-result.vue'
import { setItem, getItem } from '@/utils/storage'
export default {
  // 组件名称
  name: 'SearchIndex',
  // 局部注册的组件
  components: {
    searchHistory,
    searchSuggestion,
    searchResult
  },
  // 组件参数 接收来自父组件的数据
  props: {},
  // 组件状态值
  data () {
    return {
      searchText: '',
      isResultShow: false, // 控制搜索展示
      searchHistories: getItem('TOUTIAO_SEARCH_HISTORIES') || []
    }
  },
  // 计算属性
  computed: {},
  // 侦听器
  watch: {
    searchHistories (val) {
      setItem('TOUTIAO_SEARCH_HISTORIES', val)
    }
  },
  // 生命周期钩子   注：没用到的钩子请自行删除
  /**
  * 组件实例创建完成，属性已绑定，但DOM还未生成，el属性还不存在
  */
  created () { },
  /**
  * el 被新创建的 vm.el 替换，并挂载到实例上去之后调用该钩子。
  * 如果 root 实例挂载了一个文档内元素，当 mounted 被调用时 vm.el 也在文档内。
  */
  mounted () { },
  // 组件方法
  methods: {
    onSearch (val) { // 搜索框搜索了触发
      this.searchText = val
      const searchHistories = this.searchHistories
      searchHistories.unshift(val)
      // 网历史记录数组里添加数据
      this.searchHistories = Array.from(new Set(searchHistories))
      this.isResultShow = true
    },
    onCancel () {
      this.$router.go(-1)
    }
  }
}
</script>

<style scoped lang="less">
.search-container {
  padding-top: 108px;
  .van-search__action {
    color: #fff;
  }
  .search-form {
    position: fixed;
    top: 0;
    right: 0;
    left: 0;
    z-index: 1;
  }
}
</style>
